import { Cascader, CascaderProps, Form, Input, message, Select } from "antd"
import { Children, useEffect, useState } from "react";
import HomePage_ModalComponent_CancelAndSubmitFooterComponent from "../../../../../../component/modal/component/cancelAndSubmitFooter"
import { ReactComponent as CascaderArrow } from "../../../../../../../../assets/svg/cascaderArrow.svg"
import lessModule from "./index.module.less";
import { $Http } from "../../../../../../../../network";
import { $eventBus, $FilterOrganizationRank, $selectOptionData } from "../../../../../../../../common/utils";


// 主页-账号管理页面-操作弹窗组件
interface homePageSystemSettingsPageAccountManagementPageModalComponnetInterface {
    sourceData: object
    change_cancel: Function

}
const HomePage_SystemSettingsPage_AccountManagementPage_ModalComponnet: React.FC<homePageSystemSettingsPageAccountManagementPageModalComponnetInterface> = (props) => {
    const [form] = Form.useForm();
    const [formItemList, setFormItemList] = useState<Array<object>>([]);
    const [cascaderList, setCascaderList] = useState<Array<any>>([]);
    const teamList = [
        {
            label: "团队名称",
            key: "name",
            type: "input",
            placeholder: '请输入'
        }
    ]
    const departmentList = [
        {
            label: "部门名称",
            type: "input",
            key: "name",
            placeholder: '请输入'
        },
        {
            label: "所属团队",
            type: "cascader",
            key: "organization",
            placeholder: '请选择',
        }
    ]
    const positionList = [
        {
            label: "职位名称",
            type: "input",
            key: "name",
            placeholder: '请输入'
        },
        {
            label: "所属部门",
            type: "cascader",
            key: "organization",
            placeholder: '请选择',
            ruleData: ({ getFieldValue }) => ({
                validator(data:object, value:Array<string>) {
                    if (!value || value.length === 2) {
                        return Promise.resolve();
                    }
                    return Promise.reject(new Error('请选择至部门'));
                },
            })
        },
    ]
    const accountList = [
        {
            label: "账户名称",
            type: "input",
            key: "username",
            placeholder: '请输入'
        },
        {
            label: "账号密码",
            type: "input",
            key: "password",
            placeholder: '请输入'
        },
        {
            label: "所属职位",
            type: "cascader",
            key: "organization",
            placeholder: '请选择',
            ruleData: ({ getFieldValue }) => ({
                validator(data:object, value:Array<string>) {
                    if (!value || value.length === 3) {
                        return Promise.resolve();
                    }
                    return Promise.reject(new Error('请选择至职位'));
                },
            })

        },
        {
            label: "账号权限类型",
            type: "select",
            key: "power",
            optionList: [{ label: "超级管理员" }, { label: "管理员" }, { label: "普通用户" }],
            placeholder: '请选择'
        },
        {
            label: "性别",
            type: "select",
            key: "gender",
            placeholder: '请选择',
            optionList: $selectOptionData["gender"]
        },
        {
            label: "联系电话",
            type: "input",
            key: "tel",
            placeholder: '请输入'
        },
    ]

    const click_submit = () => {
        form.validateFields().then((value) => {
            
            value["organization"] = value["organization"]?.map((item:string)=>parseInt(item.split("-")[1]))
            const paramsData = {
                rank: $FilterOrganizationRank(props.sourceData["rank"]),
                ...value,
            }

            $Http(props.sourceData["operation"] === "新建" ? "create" : "edit", {typeName: `系统设置/账号管理${ props.sourceData["rank"] !== "账号" ? "/组织管理" :""}` ,...paramsData, ...(props.sourceData["operation"] === "编辑" && { id: props.sourceData["id"] })}).then((res) => {
                message.success(res["success"])
                setTimeout(() => {
                    $FilterOrganizationRank(props.sourceData["rank"]) === "user" ? 
                        $eventBus.emit("headerOperationConditionSwitch", { source: "HomePage_SystemSettingsPage_AccountManagementPage_ModalComponnet", explain: "请关闭头部操作条件，并查询", data: { isOpen: false } })
                        : $eventBus.emit("updateOrganization", { source: "HomePage_SystemSettingsPage_AccountManagementPage_ModalComponnet", explain: "新增或编辑已完成，请更新组织数据" })
                    props.change_cancel()
                });
            })
        })
    }

    const customLabelRender = (data: object, key: string) => {
        
        const organizationList = form.getFieldValue(key)
        return (
            <div className="homePage-cascaderMenuItem" style={{ backgroundColor: organizationList?.includes(data["key"]) ? "#ECF2FE" : "#FFFFFF" }}>
                <span style={{ color: organizationList?.includes(data["key"]) ? "#0052D9" : "rgba(0, 0, 0, 0.9)" }}>{data["label"]}</span>
                {
                    data["children"] && <CascaderArrow color={organizationList?.includes(data["key"]) ? "#0052D9" : "rgba(0, 0, 0, 0.4)"} />
                }
            </div>
        );

    }

    const http_userSearchOrganization = () => {
        $Http("search", { typeName: "系统设置/账号管理/组织管理" ,rank: $FilterOrganizationRank(props.sourceData["rank"]) }).then((res) => {
            setCascaderList([...res["list"]])

        })
    }
    const change_sourceList = () => {
        switch (props.sourceData["rank"]) {
            case "团队":
                setFormItemList([...teamList])
                break;
            case "部门":
                setFormItemList([...departmentList])
                break;
            case "职位":
                setFormItemList([...positionList])
                break;
            case "账号":
                setFormItemList([...accountList])
                break;
        }
    }
    useEffect(() => {
        change_sourceList()
        http_userSearchOrganization()
    }, [])
    return (
        <div className={lessModule["homePageSystemSettingsPageAccountManagementPageModalComponnet"]} style={{ width: formItemList.length > 2 ? 700 : 500, paddingBottom: ["账号"].includes(props.sourceData["rank"]) ? 57 : ["团队"].includes(props.sourceData["rank"]) ? 38 : 37 }}>
            <header className={lessModule["homePageSystemSettingsPageAccountManagementPageModalComponnet-header"]} >{props.sourceData["operation"]}{props.sourceData["rank"]}</header>
            <main className={lessModule["homePageSystemSettingsPageAccountManagementPageModalComponnet-main"]}>
                <Form layout="vertical" className={lessModule["homePageSystemSettingsPageAccountManagementPageModalComponnetMain-form"]}
                    form={form}
                    initialValues={props.sourceData}
                >
                    {
                        formItemList.map((item, idx,) => {
                            return (
                                <Form.Item key={`formItem${idx}`} className={lessModule["homePageSystemSettingsPageAccountManagementPageModalComponnetMain-item"]}
                                    style={{ width: formItemList.length > 2 ? "calc((100% - 40px) / 2)" : "100%" }}
                                    label={`${item["label"]}：`}
                                    name={item['key']}
                                    required={false}
                                    rules={[{ required: true, message: item["placeholder"] }, item["ruleData"] ]}
                                >
                                    {item["type"] === "select" && <Select showSearch
                                        placeholder={item["placeholder"]}
                                        options={item["optionList"]}
                                        filterOption={(input, option) =>
                                            (option?.label as string ?? '').toLowerCase().includes(input.toLowerCase())
                                        }
                                        fieldNames={{ value: "label" }}
                                    />
                                    }
                                    {
                                        item["type"] === "input" && <Input placeholder={item["placeholder"]} autoComplete="off" />
                                    }
                                    {
                                        item['type'] === "cascader" && <Cascader changeOnSelect allowClear={false}
                                            defaultValue={props.sourceData[item["key"]] ?? []}
                                            placeholder={item["placeholder"]}
                                            fieldNames={{ value: "key" }}
                                            options={cascaderList}
                                            optionRender={(data) => customLabelRender(data, item["key"])} // 使用自定义标签渲染  
                                        ></Cascader>
                                    }
                                </Form.Item>
                            )
                        })

                    }
                </Form>
            </main>
            <HomePage_ModalComponent_CancelAndSubmitFooterComponent flexGap={40} fontSize={20} submitName="确认" change_cancel={props.change_cancel} change_submit={click_submit} />
        </div>
    )
}
export default HomePage_SystemSettingsPage_AccountManagementPage_ModalComponnet

